﻿using System;
using System.Collections.Generic;
using Company.Merchandising.BusinessLayer.DataTransferObjects;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;
using Company.Merchandising.ServiceLayer.EntityManagement;
using Telerik.Web.UI;
using WebApplication.Code;

namespace WebApplication.Restricted.Management.Company
{
	public partial class CompanyManagementPage : EntityPage
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}
		protected void CompaniesGrid_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
		{
			GridEditableItem editedItem = e.Item as GridEditableItem;
			if (editedItem == null)
			{
				return;
			}

			Dictionary<string, object> newCompanyValues = new Dictionary<string, object>();
			e.Item.OwnerTableView.ExtractValuesFromItem(newCompanyValues, editedItem);
			
			DTOCompany company = ExtractCompany(newCompanyValues, editedItem, false);
			try
			{
				new CompanyManager(ModelEntities).AddCompany(company);
			}
			catch
			{
				return;
			}

		}
		protected void CompaniesGrid_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
		{
			GridEditableItem editedItem = e.Item as GridEditableItem;
			if (editedItem == null)
			{
				return;
			}

			Dictionary<string, object> newCompanyValues = new Dictionary<string, object>();
			e.Item.OwnerTableView.ExtractValuesFromItem(newCompanyValues, editedItem);

			DTOCompany company = ExtractCompany(newCompanyValues, editedItem, true);
			try
			{
				new CompanyManager(ModelEntities).UpdateCompany(company);
			}
			catch
			{
				return;
			}
		}
		protected void CompaniesGrid_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
		{
			GridEditableItem editedItem = e.Item as GridEditableItem;
			if (editedItem == null)
			{
				return;
			}

			Dictionary<string, object> newCompanyValues = new Dictionary<string, object>();
			e.Item.OwnerTableView.ExtractValuesFromItem(newCompanyValues, editedItem);

			DTOCompany company = ExtractCompany(newCompanyValues, editedItem, true);
			try
			{
				new CompanyManager(ModelEntities).DeleteCompany(company);
			}
			catch
			{
				return;
			}
		}

		protected void CompaniesGridNeedDataSource(object source, GridNeedDataSourceEventArgs e)
		{
			CompaniesGrid.DataSource = new DACCompany(ModelEntities).GetAllCompanies();
		}

		private DTOCompany ExtractCompany(Dictionary<string, object> companyValues, GridEditableItem editedItem, bool getCompanyId)
		{
			DTOCompany company = new DTOCompany();
			if (getCompanyId)
			{
				company.Id = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["Id"]);
			}

			company.Name = companyValues["Name"] as string;
			company.FullName = companyValues["FullName"] as string;
			company.IsDefault = Convert.ToBoolean(companyValues["IsDefault"]);

			return company;
		}
	}
}
